package com.hs.srm.admin.modules.requisition.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.hs.srm.admin.common.exception.UnauthorizedException;
import com.hs.srm.admin.common.util.OAConfig;
import com.hs.srm.admin.common.util.StringUtils;
import com.hs.srm.admin.modules.orders.entity.ScmPoHeaderEntity;
import com.hs.srm.admin.modules.orders.entity.ScmPoItemEntity;
import com.hs.srm.admin.modules.orders.service.ScmPoHeaderService;
import com.hs.srm.admin.modules.orders.service.ScmPoItemService;
import com.hs.srm.admin.modules.pricemanagement.entity.HistoricalPriceEntity;
import com.hs.srm.admin.modules.pricemanagement.entity.InquiryQuotationEntity;
import com.hs.srm.admin.modules.pricemanagement.service.HistoricalPriceService;
import com.hs.srm.admin.modules.pricemanagement.service.InquiryQuotationService;
import com.hs.srm.admin.modules.requisition.entity.NproPurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.entity.SampleOrderReportEntity;
import com.hs.srm.admin.modules.requisition.entity.SamplePurchRequestHeaderEntity;
import com.hs.srm.admin.modules.requisition.entity.SamplePurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.service.SampleOrderReportService;
import com.hs.srm.admin.modules.requisition.service.SamplePurchRequestHeaderService;
import com.hs.srm.admin.modules.requisition.service.SamplePurchRequestItemService;
import com.hs.srm.admin.modules.requisition.vo.SupplyGoodsEntityVO;
import com.hs.srm.admin.modules.sequence.service.SequenceService;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.admin.modules.vendor.service.SampleVendorService;
import com.hs.srm.admin.modules.vendor.service.VendorService;
import com.hs.srm.admin.modules.vendor.vo.SimpleVendorInfoVO;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.utils.DictDataUtil;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.common.utils.Constants;
import com.hs.srm.common.utils.DateUtils;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.landray.kmss.km.review.webservice.Exception_Exception;
import com.landray.kmss.km.review.webservice.IKmReviewWebserviceService;
import com.landray.kmss.km.review.webservice.IKmReviewWebserviceServiceService;
import com.landray.kmss.km.review.webservice.KmReviewParamterForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sunnykid.lang.SunnykidDate;
import sunnykid.text.SunnykidText;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 样品申请
 */
@RestController
@RequestMapping("/sampleRequest")
public class SampleRequestController extends AbstractController {

    Logger logger = LoggerFactory.getLogger(SampleRequestController.class);
    @Autowired
    private SamplePurchRequestHeaderService samplePurchRequestHeaderService;

    @Autowired
    private SamplePurchRequestHeaderService sampleHeaderService;

    @Autowired
    private SamplePurchRequestItemService sampleItemService;

    @Autowired
    private SequenceService sequenceService;

    @Autowired
    private HistoricalPriceService historicalPriceService;

    @Autowired
    private ScmPoHeaderService scmPoHeaderService;

    @Autowired
    private ScmPoItemService scmPoItemService;
    @Autowired
    private VendorService vendorService;
    @Autowired
    private SampleOrderReportService sampleOrderReportService;
    @Autowired
    private SamplePurchRequestItemService samplePurchRequestItemService;
    @Autowired
    private InquiryQuotationService inquiryQuotationService;


    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = this.sampleItemService.selectDetailPage(params);
        List<SamplePurchRequestItemEntity> list = (List<SamplePurchRequestItemEntity>) page.getList();
        list = EntityUtils.valToTxt(list);
        page.setList(list);
        return R.ok(page);
    }

    @RequestMapping("/findById")
    @ResponseBody
    public R findbypkId(@RequestParam(value = "pkId[]") String[] pkId) {
        String str = pkId[0];
        SamplePurchRequestItemEntity samplePurchRequestItemEntity = this.sampleItemService.findbypkId(str);
        return R.ok(samplePurchRequestItemEntity);
    }

    /**
     * 修改所有
     */
    @SysLog("样品请购单修改")
    @RequestMapping("/updateAll")
    @ResponseBody
    public R updateAll(String data, String pkId) {
        SamplePurchRequestItemEntity samplePurchRequestItemEntity = JSONObject.parseObject(data, SamplePurchRequestItemEntity.class);
        samplePurchRequestItemEntity.setPkId(pkId);
        samplePurchRequestItemEntity.setGoodsStatus(-2);
        this.sampleItemService.updateAll(samplePurchRequestItemEntity);
        return R.msg("更新成功!");
    }

    /**
     * 订单驳回后可修改为草稿状态
     */
    @SysLog("样品单状态修改")
    @RequestMapping("/changeStatus")
    @ResponseBody
    public R changeStatus(@RequestParam(value = "pkIds[]") String[] pkIds) {
        List<SamplePurchRequestItemEntity> samplePurchRequestItemEntity = sampleItemService.selectBatchIds(Arrays.asList(pkIds));
        samplePurchRequestItemEntity.forEach(item -> item.setGoodsStatus(SamplePurchRequestItemEntity.CAOGAO));
        boolean b = sampleItemService.updateBatchById(samplePurchRequestItemEntity);
        if (!b) {
            return R.error();
        }
        return R.ok();
    }

    /**
     * @Description 获取采购组样品申请单未处理数量
     * @Return com.hs.srm.common.utils.R 返回数据
     */
    @RequestMapping("/getCount")
    public R getCount() {
        String username = this.getUser().getUsername();
        int[] nums = new int[4];
        //所有申请单
        nums[0] = sampleItemService.selectCount(new EntityWrapper<SamplePurchRequestItemEntity>().eq("purch_group", username).eq("delete_flag", 0));
        //查未完成
        nums[1] = sampleItemService.selectCount(new EntityWrapper<SamplePurchRequestItemEntity>().eq("purch_group", username).eq("goods_status", NproPurchRequestItemEntity.CAOGAO).eq("delete_flag", 0));
        //查询询价
        nums[2] = sampleItemService.selectCount(new EntityWrapper<SamplePurchRequestItemEntity>().eq("purch_group", username).notIn("goods_status", -2, 0).eq("delete_flag", 0));
        //查询完成
        nums[3] = sampleItemService.selectCount(new EntityWrapper<SamplePurchRequestItemEntity>().eq("purch_group", username).eq("goods_status", 0).eq("delete_flag", 0));
        return R.ok(nums);
    }

    /**
     * 询价
     *
     * @param
     * @return
     */
    @RequestMapping("/inquiry/{pkId}")
    public ModelAndView inquiry(@PathVariable("pkId") String pkId) {
        List<String> pklist = new ArrayList<String>(pkId.split(",").length);
        Collections.addAll(pklist, pkId.split(","));
        //根据id获取所有样品申请数据
        List<SamplePurchRequestItemEntity> itemList = sampleItemService.selectBatchIds(pklist);
        ModelAndView modelAndView = new ModelAndView("modules/requisition/inquiry/sample_inquiry_add");
        modelAndView.addObject("itemlist", itemList);
        modelAndView.getModel().put("companyCode", itemList.get(0).getFactory());
        modelAndView.getModel().put("purchaseOrg", itemList.get(0).getPurchOrg());
        modelAndView.getModel().put("purchaseGrp", itemList.get(0).getPurchGroup());
        modelAndView.getModel().put("currency", itemList.get(0).getCurrency());
        modelAndView.getModel().put("beginDate", DateUtils.getTime());

        return modelAndView;
    }

    /**
     * 新增样品申请
     *
     * @param datalist json数据
     * @return
     */
    @SysLog("新增样品申请")
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/add")
    public R add(String datalist) {
        //获取登陆人名称
        String username = this.getUser().getName();
        JSONObject jsonObject = JSONObject.parseObject(datalist);
        String itemData = jsonObject.getString("items");
        List<SamplePurchRequestItemEntity> itemEntityList = JSONArray.parseArray(itemData).toJavaList(SamplePurchRequestItemEntity.class);
        SamplePurchRequestHeaderEntity headerEntity = new SamplePurchRequestHeaderEntity();
        //样品申请编号
        String sampleCode;
        //同步，避免并发造成样品申请编号重复
        synchronized (this) {
            //获取样品申请编号
            sampleCode = "S" + sequenceService.getNextVal("sampleCode");
        }
        headerEntity.setCreatedBy(username);
        //创建日期
        Date createDate = new Date();
        headerEntity.setCreationDate(createDate);
        headerEntity.setPurchRequestCode(sampleCode);
        headerEntity.setPurchRequestType("SAMPLE");


        //设置申请行项目的申请代码和行项目编号
        for (int i = 0; i < itemEntityList.size(); i++) {
            itemEntityList.get(i).setPurchRequestCode(sampleCode);
            itemEntityList.get(i).setPurchRequestItemCode(String.format("%05d", (i + 1) * 10));
            itemEntityList.get(i).setCreatedBy(username);
            itemEntityList.get(i).setCreationDate(createDate);
            itemEntityList.get(i).setApplier(username);
        }
        sampleHeaderService.insert(headerEntity);
        sampleItemService.insertBatch(itemEntityList);
        return R.ok(sampleCode);
    }

    /**
     * @param ids
     * @param inqids
     * @return
     */
    @RequestMapping(value = "/toAllot")
    public ModelAndView toAllot(@RequestParam(value = "ids") String ids, @RequestParam(value = "inqids") String inqids) {
        //采购申请行项目id
        String[] str = ids.split(",");
        String[] inqid = inqids.split(",");
        ArrayList<String> idList = new ArrayList<>(Arrays.asList(str));
        List<SupplyGoodsEntityVO> items = sampleItemService.getSampleDistributeById(idList);
        List<SamplePurchRequestItemEntity> itemEntities = samplePurchRequestItemService.selectBatchIds(Arrays.asList(str));
        String requestCode = null;
        //询价的id
        ArrayList<String> inqidList = new ArrayList<>(Arrays.asList(inqid));
        List<HistoricalPriceEntity> historicalPrice = historicalPriceService.findUnionVendorByIds(inqidList);
        List<SupplyGoodsEntityVO> itemList = new ArrayList<>();
        for (HistoricalPriceEntity historical : historicalPrice) {
            for (SupplyGoodsEntityVO SuVo : items) {
                SuVo.setVendorCode(historical.getVendorCode());
                SuVo.setSrmCode(historical.getSrmCode());
                SuVo.setVendorName(historical.getVendorName());
                SuVo.setTaxCode(historical.getTaxCode());
                SuVo.setCurrency(historical.getCurrency());
                SuVo.setPriceUnit(historical.getPriceUnit());
                SuVo.setTaxPrice(historical.getPrice());
                SuVo.setPayCondition(historical.getPayCondition());
                SuVo.setCreatedBy(this.getUser().getUsername());
                for (SamplePurchRequestItemEntity itemEntity : itemEntities) {
                    requestCode = itemEntity.getPurchRequestCode();
                    SuVo.setSpecification(itemEntity.getSpecification());
                }
                SamplePurchRequestHeaderEntity headerEntity = this.samplePurchRequestHeaderService.selectOne(new EntityWrapper<SamplePurchRequestHeaderEntity>().eq("purch_request_code", requestCode));
                SuVo.setSectionSupervisor(headerEntity.getSectionSupervisor());
                historical.setSrmCode(historical.getSrmCode());
                itemList.add(SuVo);
            }
        }
        List<SimpleVendorInfoVO> vendorInfoEntitylist = this.vendorService.findSimpleAll();
        ModelAndView modelAndView = new ModelAndView("modules/requisition/sample_goodsDistribution_edit");
        modelAndView.addObject("itemlist", itemList);
        String jsonStr = JSON.toJSONString(vendorInfoEntitylist);
        modelAndView.addObject("vendorInfoEntitylist", jsonStr);
        return modelAndView;
    }


    /**
     * 货源指定信息
     */
    @SysLog("货源指定信息")
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/updateSource")
    public synchronized R updateSource(@RequestBody JSONObject obj) {
        //解析json数据
        JSONObject json = JSON.parseObject(obj.toJSONString());
        SamplePurchRequestHeaderEntity sampleRequestHeader;
        //订单数据
        ScmPoHeaderEntity scmPoHeaderEntity = new ScmPoHeaderEntity();
        ScmPoItemEntity scmPoItemEntity;
        List<ScmPoItemEntity> ScmPoItemList = new ArrayList<>();
        List<HistoricalPriceEntity> historicalPriceList = new ArrayList<>();
        //采购申请行项目
        List<SamplePurchRequestItemEntity> entityList;
        JSONArray itmeList = JSONArray.parseArray(json.getString("supplyGoodsEntity"));
        Timestamp date;
        //1.查询最大订单号
        String poNo = scmPoHeaderService.selectnum();
        //2.查询最大订单号
        int edition = 0;
        //3.String 转换成int
        int suffix = 0;
        String po_no = "";
        if ("".equals(poNo) || poNo == null) {
            suffix = 0;
            edition = 0;
        } else {
            suffix = Integer.parseInt(poNo.substring(3));
            edition = this.scmPoHeaderService.getEdition();
        }
        // 看版本号是否和查出来的一至
        if (suffix == edition) {
            edition++;
            suffix++;
            po_no = StringUtils.makeStr("480", suffix, 7).replaceAll(" ", "0");
            for (int i = 0; i < itmeList.size(); i++) {
                // 去掉value为空的键值对
                JSONObject jo = JSONObject.parseObject(JSONObject.parseObject(itmeList.getString(i)).toString().replaceAll(",\"\\w+\":\"\"", ""));
                entityList = new ArrayList<>();
                sampleRequestHeader = new SamplePurchRequestHeaderEntity();
                scmPoItemEntity = new ScmPoItemEntity(); //订单行项目
                if (!jo.isEmpty()) {
                    //1、使用JSONObject
                    //订单行项目数据  //measureUnit
                    SupplyGoodsEntityVO supplyGoodsEntity = JSONObject.toJavaObject(jo.getJSONObject("SupplyGoodsEntityVO"), SupplyGoodsEntityVO.class);
                    scmPoItemEntity.setPoItemId(SunnykidText.getUUID());//主键id
                    scmPoItemEntity.setPrNo(supplyGoodsEntity.getPurchRequestCode()); //采购申请编码
                    //生成订单行项目号 00010,00020...
                    scmPoItemEntity.setItemNo(String.format("%05d", (i + 1) * 10));
                    //请购行项目号
                    scmPoItemEntity.setPrItemNo(supplyGoodsEntity.getPurchRequestItemCode());
                    scmPoItemEntity.setSubjectCategory(supplyGoodsEntity.getSubjectCategory());//科目类别
                    scmPoItemEntity.setMaterialDesc(supplyGoodsEntity.getMaterialDesc());//物料描述
                    scmPoItemEntity.setFactory(supplyGoodsEntity.getFactory());//工厂
                    scmPoItemEntity.setStorageLocation(supplyGoodsEntity.getStorageLocation());//库存地点
                    scmPoItemEntity.setInternalPoNo(supplyGoodsEntity.getInternalOrderCode());//内部订单号
                    scmPoItemEntity.setSpecification(supplyGoodsEntity.getSpecification());
                    if (supplyGoodsEntity.getMaterialCode() != null) {
                        scmPoItemEntity.setMaterialCode(supplyGoodsEntity.getMaterialCode());//物料号
                        scmPoHeaderEntity.setPoFlag("PRO"); //非生产 NPRO  生产 PRO
                    } else {
                        scmPoHeaderEntity.setPoFlag("NPRO"); //非生产 PRO  生产 PRO
                        scmPoItemEntity.setMaterialCode(supplyGoodsEntity.getLedgerAccount());//总账科目，放入物料编码字段，同步SAP时从物料编码中取出总账科目
                    }
                    scmPoItemEntity.setMaterialGroup(supplyGoodsEntity.getMaterialGroup());//物料组
                    scmPoItemEntity.setRequester(supplyGoodsEntity.getApplier());//申请者
                    scmPoItemEntity.setPoCount(supplyGoodsEntity.getQuantity());//采购订单数量
                    scmPoItemEntity.setPoPrice(supplyGoodsEntity.getTaxPrice()); //含税单价
                    scmPoItemEntity.setPoUnit(supplyGoodsEntity.getMeasureUnit()); //订单货物的计量单位
                    scmPoItemEntity.setPriceUnit(supplyGoodsEntity.getPriceUnit());//采购订单的计量单位(需求是最小起订数量)
                    scmPoItemEntity.setTaxCode(supplyGoodsEntity.getTaxCode());//税码
                    scmPoItemEntity.setDeliveryDate(supplyGoodsEntity.getRequestDate());//样品需求日期
                    scmPoItemEntity.setCostCenter(supplyGoodsEntity.getCostCenter()); //成本中心
                    scmPoItemEntity.setPoNo(po_no); //订单编号
                    scmPoItemEntity.setItemUuid(supplyGoodsEntity.getPkId()); //行项目id
                    scmPoItemEntity.setCreatedBy(this.getUser().getUsername());//创建者
                    date = DateUtils.currentTimestamp();
                    scmPoItemEntity.setCreationDate(date);//创建时间
                    if (supplyGoodsEntity.getReason() != null) {
                        scmPoItemEntity.setReason(supplyGoodsEntity.getReason());
                    } else {
                        scmPoItemEntity.setReason(0);
                    }

                    //备注
                    scmPoItemEntity.setRemark(supplyGoodsEntity.getRemark());
                    //通过采购申请编码得到对应的id
                    sampleRequestHeader = sampleHeaderService.findByNo(supplyGoodsEntity.getPurchRequestCode());
                    /*******处理订单抬头****************/
                    scmPoHeaderEntity.setPoId(SunnykidText.getUUID());
                    scmPoHeaderEntity.setPoNo(po_no);
                    scmPoHeaderEntity.setSectionSupervisor(sampleRequestHeader.getSectionSupervisor());//部门主管
                    if (supplyGoodsEntity.getSrmCode() != null) {
                        scmPoHeaderEntity.setSrmCode(supplyGoodsEntity.getSrmCode());//临时供应商代码
                    } else {
                        scmPoHeaderEntity.setSrmCode("");
                    }
                    scmPoHeaderEntity.setPoType(supplyGoodsEntity.getPurchRequestType());//订单类型
                    //科目类别 ==采购凭证类别
                    scmPoHeaderEntity.setPoCategory(supplyGoodsEntity.getSubjectCategory()); //采购凭证类别
                    scmPoHeaderEntity.setVendorId(supplyGoodsEntity.getVendorCode()); //以后供应商编码作为供应商的ID
                    //将8001/8002/8003工厂对应公司代码改为8888
                    if (supplyGoodsEntity.getFactory().equals("8001") || supplyGoodsEntity.getFactory().equals("8002") || supplyGoodsEntity.getFactory().equals("8003")) {
                        scmPoHeaderEntity.setCompanyCode("8888");
                    } else {
                        scmPoHeaderEntity.setCompanyCode(supplyGoodsEntity.getFactory());//公司代码
                    }
                    scmPoHeaderEntity.setPurchGroup(supplyGoodsEntity.getPurchGroup()); //采购组

                    //采购组织， 除1700和1800，其他工厂采购组织1000,1700和1800采购组织1400
                    if (supplyGoodsEntity.getFactory().equals("1700") || supplyGoodsEntity.getFactory().equals("1800")) {
                        scmPoHeaderEntity.setPurchOrg("1400");
                    } else {
                        //supplyGoodsEntity.getPurchOrg()
                        scmPoHeaderEntity.setPurchOrg("1000");
                    }
                    scmPoHeaderEntity.setSectionSupervisor(supplyGoodsEntity.getSectionSupervisor());//部门主管
                    scmPoHeaderEntity.setCreationDate(date);//创建时间
                    scmPoHeaderEntity.setCreatedBy(this.getUser().getUsername());//创建者
                    if ("".equals(supplyGoodsEntity.getPayCondition()) || supplyGoodsEntity.getPayCondition() == null) {
                        scmPoHeaderEntity.setPayCondition("");//付款条件代码
                    } else {
                        scmPoHeaderEntity.setPayCondition(supplyGoodsEntity.getPayCondition());//付款条件代码
                    }
                    if ("".equals(supplyGoodsEntity.getI18nTradeTerms()) || supplyGoodsEntity.getI18nTradeTerms() == null) {
                        scmPoHeaderEntity.setI18nTradeTerms("");//国际贸易条款
                    } else {
                        scmPoHeaderEntity.setI18nTradeTerms(supplyGoodsEntity.getI18nTradeTerms());//国际贸易条款
                    }
                    scmPoHeaderEntity.setCurrencyCode(supplyGoodsEntity.getCurrency()); //货币币种
                    scmPoHeaderEntity.setCompanyName(supplyGoodsEntity.getVendorName());//供应商名称
                    scmPoHeaderEntity.setEdition(edition);//版本控制
                    /**************采购订单行项目*******************/
                    scmPoHeaderEntity.setStatus(0);
                    SamplePurchRequestItemEntity sampleRequestItemEntity = sampleItemService.selectById(supplyGoodsEntity.getPkId());
                    sampleRequestItemEntity.setGoodsStatus(0);
                    entityList.add(sampleRequestItemEntity);
                    //订单行项目
                    ScmPoItemList.add(scmPoItemEntity);
                    //样品 生成订单时把价格保存到历史订单中
                    if (historicalPriceService.convertToHistoryPrice(supplyGoodsEntity) != null) {
                        historicalPriceList.add(historicalPriceService.convertToHistoryPrice(supplyGoodsEntity));
                    }
                }
                if (sampleRequestHeader != null && entityList.size() > 0) {
                    //货源已指定状态
                    sampleRequestHeader.setGoodsStatus(0);
                    sampleHeaderService.updateById(sampleRequestHeader);
                    sampleItemService.updateBatchById(entityList);
                }

            }

            this.scmPoHeaderService.insertOrUpdate(scmPoHeaderEntity);
            this.scmPoItemService.insertBatch(ScmPoItemList);

            if (!CollectionUtils.isEmpty(historicalPriceList)) {
                historicalPriceService.insertBatch(historicalPriceList);
            }
        }
        return R.ok().put("poNo", po_no);

    }

    /**
     * 删除样品请购单
     */
    @SysLog("删除样品请购单")
    @RequestMapping("/deletePkId")
    public R delete(@RequestParam("pkId[]") String[] pkId) {
        List<SamplePurchRequestItemEntity> list = this.sampleItemService.selectBatchIds(Arrays.asList(pkId));
        for (SamplePurchRequestItemEntity samplePurchRequestItemEntity : list) {
            samplePurchRequestItemEntity.setDeleteFlag("1");
        }
        this.sampleItemService.updateBatchById(list);
        return R.ok();
    }

    /**
     * 样品单入库通知通知采购员
     */
    @RequestMapping("/sampleNotice")
    public R sampleNotice(Map<String, Object> map) {
        String userId = this.getUser().getUsername();
        List<ScmPoHeaderEntity> headerEntityList = samplePurchRequestHeaderService.findPoNo();
        List<ScmPoItemEntity> itemEntityList = samplePurchRequestHeaderService.findItemPoNo();
        for (ScmPoHeaderEntity scmPoHeaderEntity : headerEntityList) {
            String purchGroup = scmPoHeaderEntity.getPurchGroup();
            if (userId.equals(purchGroup)) {
                for (ScmPoItemEntity scmPoItemEntity : itemEntityList) {
                    String type = scmPoHeaderEntity.getPoType();
                    if (type.equals("SAMPLE")) {
                        String itemNo = scmPoItemEntity.getItemNo();
                        map.put("itemNo", itemNo);
                        map.put("poNo", scmPoHeaderEntity.getPoNo());
                        Date createTime = scmPoHeaderEntity.getCreatetime();
                        String time = DateUtils.format(createTime, DateUtils.DATE_TIME_PATTERN);
                        map.put("time", time);
                    }
                }
            }
        }
        return R.ok(map);
    }

    /**
     * 样品单导入oa
     */
    @RequestMapping(value = "/toOa", method = RequestMethod.POST)
    public R toOa(SampleOrderReportEntity sampleOrderReportEntity) {
        URL wsdlURL = null;
        try {
            wsdlURL = new URL("http://" + OAConfig.host + ":" + OAConfig.port
                    + "/ekp/sys/webservice/kmReviewWebserviceService?wsdl");

        } catch (MalformedURLException ex) {
            return R.error("OA接口地址错误！");
        }
        IKmReviewWebserviceServiceService ss = new IKmReviewWebserviceServiceService(wsdlURL, Constants.SERVICE_NAME);
        IKmReviewWebserviceService port = ss.getIKmReviewWebserviceServicePort();

        KmReviewParamterForm _addReview_arg0;
        //判断是否存在OA账号，为空则返回错误
        try {
            _addReview_arg0 = createForm(sampleOrderReportEntity);
        } catch (UnauthorizedException e) {
            return R.error(e.getMessage());
        }

        String _addReview__return = null;
        try {
            _addReview__return = port.addReview(_addReview_arg0); // 启动流程的返回值（流程id）
        } catch (Exception_Exception e) {
            System.out.println("Expected exception: Exception has occurred: " + e.toString());
        }
        if (_addReview__return == null) {
            return R.error("提交OA流程失败！");
        }
        sampleOrderReportEntity.setState(1);
        sampleOrderReportEntity.setOaDocId(_addReview__return);
        this.sampleOrderReportService.updateById(sampleOrderReportEntity);
        return R.ok();
    }

    /**
     * 封装样品报告的各项参数
     *
     * @return KmReviewParamterForm
     */
    private KmReviewParamterForm createForm(SampleOrderReportEntity sampleOrderReportEntity) {
        // 文档模板id
        KmReviewParamterForm form = new KmReviewParamterForm();
        // 测式系统中的模板id：17065d5a899a9c5c37055ec45c2b710e
        // 17065d5a899a9c5c37055ec45c2b710e
        //17065d5a899a9c5c37055ec45c2b710e
        form.setFdTemplateId(OAConfig.sampleTemplateId);
        // 文档标题
        form.setDocSubject("样品单审批");

        // 流程发起人
        SysUserEntity user = this.getUser();
        String loginName = user.getOaAccount();
        if (loginName == null || "".equals(loginName)) {
            throw new UnauthorizedException("OA账号为空，请添加OA账号！");
        }
        form.setDocCreator("{\"LoginName\":\"" + loginName + "\"}");
        //测试账号
        //form.setDocCreator("{\"LoginName\":\"2183603\"}");
        // 文档关键字
        form.setFdKeyword("[\"样品单\",  \"采购\"]");
        JSONObject formValues = null;
        /**
         *      模板id：17065d5a899a9c5c37055ec45c2b710e
         * 		申请试用单位主管:fd_section_supervisor
         * 		供应商名称:fd_vendor_name
         * 		物料描述：fd_material_desc
         * 		物料号：fd_material_code
         * 		数量：fd_count
         * 		规格：fd_specification
         * 		次数:fd_reason
         * 		申请单位:fd_applicant
         * 		日期：fd_creation_date
         */
        formValues = new JSONObject();
        //formValues.put("fd_pk_id", sampleOrderReportEntity.getPkId());//样品单id
        formValues.put("fd_section_supervisor", sampleOrderReportEntity.getSectionSupervisor());//申请试用单位主管
        formValues.put("fd_vendor_name", sampleOrderReportEntity.getVendorName());//供应商名称
        formValues.put("fd_material_code", sampleOrderReportEntity.getMaterialCode());//物料描述
        formValues.put("fd_material_desc", sampleOrderReportEntity.getMaterialDesc());//物料号
        formValues.put("fd_count", sampleOrderReportEntity.getCount());//数量
        formValues.put("fd_specification", sampleOrderReportEntity.getSpecification());//规格
        formValues.put("fd_creation_date", sampleOrderReportEntity.getCreationDate());//日期
        formValues.put("fd_reason", sampleOrderReportEntity.getReason());//次数
        formValues.put("fd_apply", sampleOrderReportEntity.getApply());//申请人
        formValues.put("fd_measure_unit", sampleOrderReportEntity.getMeasureUnit());//订单单位
        form.setFormValues(formValues.toJSONString());
        this.sampleOrderReportService.updateById(sampleOrderReportEntity);
        return form;
    }


    /**
     * 货源指定了状态下的货源分配
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/toSpecifyAllot")
    public ModelAndView toSpecifyAllot(@RequestParam(value = "ids") String ids, @RequestParam(value = "requestCode") String requestCode) {
        //采购订单行项目id
        String str[] = ids.split(",");
        //采购订单行项目id
        String requestCodes[] = requestCode.split(",");
        //修改 2019-07-09
        ArrayList<String> idsarrayList = new ArrayList<String>(Arrays.asList(str));
        /**********2019-06-23  yanfei**********************/
        List<SupplyGoodsEntityVO> itemlisttem = sampleItemService.getSampleDistributeById(idsarrayList);
        /*******2019-07-09 yanfei*********************/
        //比价审核通过的信息
        List<String> inqidList = new ArrayList<>();
        List<InquiryQuotationEntity> inquiryQuotationEntities = this.inquiryQuotationService.selectList(new EntityWrapper<InquiryQuotationEntity>().eq("request_code", requestCodes[0]).eq("state_", 3));
        /**********2019-07-26**********************/
        List<SupplyGoodsEntityVO> itemlist = new ArrayList<SupplyGoodsEntityVO>();
        List<SamplePurchRequestItemEntity> itemEntities = samplePurchRequestItemService.selectBatchIds(Arrays.asList(str));

        for (int i = 0; i < inquiryQuotationEntities.size(); i++) {
            String payCondition = this.vendorService.selectByVendorCode(inquiryQuotationEntities.get(i).getVendorCode()).getPayCondition();
            for (SupplyGoodsEntityVO SuVo : itemlisttem) {
                if (inquiryQuotationEntities.get(0).getRequestCode().equals(inquiryQuotationEntities.get(i).getRequestCode())
                        && inquiryQuotationEntities.get(i).getMaterialDesc().equals(SuVo.getMaterialDesc())) {
                    SuVo.setVendorCode(inquiryQuotationEntities.get(i).getVendorCode());
                    SuVo.setVendorName(inquiryQuotationEntities.get(i).getVendorName());
                    SuVo.setTaxCode(inquiryQuotationEntities.get(i).getTaxCode());
                    SuVo.setCurrency(inquiryQuotationEntities.get(i).getCurrency());
                    SuVo.setPriceUnit(inquiryQuotationEntities.get(i).getPriceUnit());
                    SuVo.setPayCondition(payCondition);
                    SuVo.setTaxPrice(new BigDecimal(inquiryQuotationEntities.get(i).getLastEnquiryPrice()));
                    SuVo.setCreatedBy(this.getUser().getUsername());
                    for (SamplePurchRequestItemEntity itemEntity : itemEntities) {
                        requestCode = itemEntity.getPurchRequestCode();
                        SuVo.setSpecification(itemEntity.getSpecification());
                    }
                    SamplePurchRequestHeaderEntity headerEntity = this.samplePurchRequestHeaderService.selectOne(new EntityWrapper<SamplePurchRequestHeaderEntity>().eq("purch_request_code", requestCode));
                    SuVo.setSectionSupervisor(headerEntity.getSectionSupervisor());
                    itemlist.add(SuVo);
                }
            }
        }

        /*******2019-07-09 yanfei*********************/
        //自动补全功能
        List<SimpleVendorInfoVO> vendorInfoEntitylist = this.vendorService.findSimpleAll();
        ModelAndView modelAndView = new ModelAndView("modules/requisition/sample_goodsDistribution_edit");
        modelAndView.addObject("itemlist", itemlist);
        String jsonStr = JSON.toJSONString(vendorInfoEntitylist);
        modelAndView.addObject("vendorInfoEntitylist", jsonStr);
        return modelAndView;
    }
}
